
import puppeteer, { Browser, Page } from 'puppeteer';
// import { minPng } from "./minPng";
const handlebars = require('handlebars');
const { execSync } = require('child_process');
// const psList = require('ps-list');
// const psTree = require('ps-tree');
const fs = require('fs');
const path = require('path');
const compiledTemplatesCache = new Map();
const dir = path.resolve(__dirname, '../../../');

import sharp from 'sharp';
export enum tempDir {
    属性模板 = `page/att_body`,
    技能模板 = `page/skill`,
    天赋模板 = `page/talent`,
    血统模板 = `page/job`,
    称号模版 = `page/title`,
    宠物属性模板 = "page/att_body_pet",
    等级模板 = 'page/rank',
    道具模板 = `page/panel_prop`,
    装备模板 = `page/equip`,
    名人堂 = `page/Hof`,
    主神商店 = `page/godShop`,
    通用文字 = `page/textToimg`
}
let sizeMap = new Map();
sizeMap.set(tempDir.主神商店, { width: 600, height: 850 })
sizeMap.set(tempDir.通用文字, { width: 430, height: 10 })
sizeMap.set(tempDir.属性模板, { width: 600, height: 850 })
sizeMap.set(tempDir.宠物属性模板, { width: 375, height: 667 })
sizeMap.set(tempDir.技能模板, { width: 414, height: 896 })
sizeMap.set(tempDir.天赋模板, { width: 295, height: 414 })
sizeMap.set(tempDir.血统模板, { width: 295, height: 414 })
sizeMap.set(tempDir.称号模版, { width: 756, height: 414 })
sizeMap.set(tempDir.等级模板, { width: 639, height: 380 })
sizeMap.set(tempDir.道具模板, { width: 615, height: 414 })
sizeMap.set(tempDir.装备模板, { width: 500, height: 749 })
sizeMap.set(tempDir.名人堂, { width: 600, height: 251 })
class browser {
    private init: boolean = false;
    private page: { id: number, page: Page, work: boolean }[] = []
    private browser: Browser
    constructor() {

    }
    async getCompiledTemplate(temp,dir) {
        let compiledTemplate = compiledTemplatesCache.get(temp);
        if (!compiledTemplate) {
            const templateContentPromise = fs.promises.readFile(`${dir}/html/${temp}.html`, 'utf-8');
            const templateContent = await templateContentPromise;
            compiledTemplate = handlebars.compile(templateContent);
            compiledTemplatesCache.set(temp, compiledTemplate);
        }
        return compiledTemplate;
    }
    private getAllProcesses() {
        const output = execSync('tasklist /fo csv', { encoding: 'utf8' });
        return output.split('\r\n').map(line => line.trim());
    };

    // 在启动项目时检测未关闭的进程
    private checkForUnclosedProcesses() {
        const allProcesses = this.getAllProcesses();
        try {
            for (let i = 1; i < allProcesses.length; i++) {
                const processInfo = allProcesses[i].split('","');
                const processName = processInfo[0].replace(/"/g, '');

                if (processName.includes('chrome.exe')) {
                    const pid = processInfo[1];
                    try {
                        execSync(`taskkill /PID ${pid} /F`);
                    } catch (error) {

                    }
                    console.log(`已关闭进程：${processName} (PID: ${pid})`);
                }
            }

            console.log('所有 Puppeteer 启动的浏览器进程已关闭！');
        } catch (error) {
            console.error('关闭进程时出现错误：', error);
        }
    };
    async _init() {
        try {
            await this.checkForUnclosedProcesses();
        } catch (error) {

        }
        this.browser = await puppeteer.launch({
            headless: true,// 设置为 false，启动非无头模式，即打开可视化的浏览器窗口
            args: ['--no-sandbox']
        });
        this.init = true;
        // await this.addPage()
    }
    private async addPage() {
        const page = await this.browser.newPage();
        let item = { id: this.page.length, page: page, work: false }
        this.page.push(item);
        return item;
    }
    private async getPage() {
        for (let index = 0; index < this.page.length; index++) {
            const element = this.page[index];
            if (!element.work) {
                return element;
            }
        }
        return await this.addPage();
    }
    async render(temp: string, data: any): Promise<string> {
        if (!this.init) {
            console.error('browser 未初始化');
            return '';
        }
        const outId = `${Date.now()}`;
        const _data = data || {};

        // 异步读取并编译模板

        const compiledTemplate = await this.getCompiledTemplate(temp,dir)
        
        const finalRenderedTemplate = compiledTemplate(_data);

        // 保存渲染后的网页为HTML文件
        await fs.promises.writeFile(`${dir}/html/output_html/${outId}.html`, finalRenderedTemplate);
        const tempHtml = `file://${dir}/html/output_html/${outId}.html`;

        let ins = await this.getPage();

        await ins.page.setViewport(sizeMap.get(temp));
        ins.work = true;
        await ins.page.goto(tempHtml, { waitUntil: 'networkidle2' });
        const imagePath = `${dir}/html/public/${outId}.png`;
        // 截取页面截图并保存为图片
        await ins.page.screenshot({ path: imagePath, fullPage: true });
        // 使用 sharp 压缩图片
        let sharpData = await sharp(imagePath)
            // .resize(1024) // 可以调整尺寸，或者不调整尺寸直接压缩
            // .jpeg({ quality: 90 })
            .toFormat('jpg')
            .toBuffer()
        await fs.promises.writeFile(imagePath, sharpData)
        ins.work = false;

        // ins.page.close()
        return `./html/public/${outId}.png`;
    }
}
export default new browser();